from apps.user.models import UserModel
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from .exception import AuthenticateError
from .auth_token import decode_token


class DefaultAuthentication(BaseAuthentication):
    def authenticate_header(self, request):
        # 如果使用AuthenticationFailed
        # 没有返回字符串时，状态码是403，写了状态码是401
        return "API"

    def authenticate(self, request):
        # 获取token
        token = request.META.get("HTTP_TOKEN")  # 从请求头中获取
        if not token:
            token = request.COOKIES.get("token")  # 从cookies中获取token
        if not token:
            token_error = "没有携带token"
            raise AuthenticateError(token_error)
        """
        1、切割
        2、解密第二段/判断过期
        3、验证第三段合法性
        """
        # 导入settings中的字符串做盐
        try:
            is_true, ret_tuple = decode_token(token)
            # 获取用户信息
            if is_true:
                username, exp_time = ret_tuple
                obj = UserModel.objects.filter(
                    account=username, is_deleted=False
                ).first()
                if obj:
                    # 在视图中通过request.user,request.auth获取
                    return username, token
                else:
                    token_error = "无此用户,请确定用户是否有效"
                    raise AuthenticateError(token_error)
            else:
                token_error = "token有问题"
                raise AuthenticateError(token_error)
        except Exception:
            token_error = "token有问题，请重新登录"
            raise AuthenticateError(token_error)
